
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using Vampirewal.BlogCore.DataAccess;
using Yitter.IdGenerator;

namespace Vampirewal.BlogCore.TestWebApi;

public class Program
{
    public static void Main(string[] args)
    {
        App.RunBlog(args, html =>
        {
            html.SetTitle("VampirewalBlog博客")
                .SetKeywords("haha")
                .SetDescription("测试博客")
                .SetIcoPath("/assets/logo.ico")
                .SetLogoPath("/assets/Vampirewal-Logo.png")
                .SetTopMenu(top =>
                {
                    TopMenu top1 = new TopMenu()
                    {
                        Id = "0",
                        Name = "项目地址",
                        Children = new List<TopMenu>()
                        {
                                new TopMenu()
                                {
                                    Id="0-1",
                                    Name="Gitee",
                                    Control=App.CreateLink("Gitee",href:"https://gitee.com/vampirewal/vampirewal.blogcore",targetType: LinkTargetType.Blank)
                                }
                        }
                    };

                    top.Add(top1);
                })
                .SetOpenLoginAuth("N184dov6Y2WMg4Aatb5X4Z", "vampirewal",TimeSpan.FromSeconds(10));


        }, service =>
        {
            service.AddBlogOptions<DbBaseOptions>();
            service.AddBlogOptions<TestOptions>();


            UserManager user = new UserManager() { Name = "测试" };

            service.AddSingleton(user);

            service.AddSqlSugar();

            

        }, app =>
        {
            app.UseForwardedHeaders();

            app.UseRouting();

            

        }, app =>
        {

        }, Config_OnLoading, Config_OnLoaded,Config_OnAuthCheck);


    }

    private static bool Config_OnAuthCheck(string username, string password)
    {
        if (username == "admin" && password == "123")
        {
            return true;
        }
        return false;
    }

    private static void Config_OnLoaded(HttpRequest request, string html)
    {

    }

    private static void Config_OnLoading(HttpRequest request)
    {
        var ip = App.GetLocalhost(request);

        if (request.Headers.ContainsKey("X-Forwarded-For"))
        {
            // X-Forwarded-For可能包含多个IP地址，逗号分隔，第一个是非代理的客户端IP
            string xForwardedFor = request.Headers["X-Forwarded-For"];
            string[] addresses = xForwardedFor.Split(',');
            string clientIp = addresses.FirstOrDefault().Trim(); // 获取第一个IP地址作为客户端IP
            Console.WriteLine($"客户端真实IP: {clientIp}");
        }
        else
        {
            // 如果没有通过代理，则直接使用RemoteIpAddress
            string clientIp = request.HttpContext.Connection.RemoteIpAddress.ToString();
            Console.WriteLine($"客户端真实IP: {clientIp}");
        }

    }
}

public class TestLogin
{
    public string Username { get; set; }

    public string Password { get; set; }
}

public class UserManager
{
    public string Name { get; set; }
}

public class TestOptions : IBlogOption<TestOptions>
{
    /// <summary>
    /// Nuget版本
    /// </summary>
    public string NugetVersion { get; set; }
}


public class TestDBConfig : SqlSugarConfig
{
    public override void DataExecuting(object OldValue, DataFilterModel entityInfo)
    {
        if (entityInfo.OperationType == DataFilterType.InsertByObject)
        {
            // 若主键是长整型且空则赋值雪花Id
            if (entityInfo.EntityColumnInfo.IsPrimarykey)
            {
                if (entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
                {
                    var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
                    if (id == null || (long)id == 0)
                        entityInfo.SetValue(YitIdHelper.NextId());
                }
                else if (entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string))
                {
                    var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
                    if (id == null || string.IsNullOrEmpty(id.ToString()))
                        entityInfo.SetValue(Guid.NewGuid().ToString());
                }

            }
            // 若创建时间为空则赋值当前时间
            else if (entityInfo.PropertyName == "CreateTime" && entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue) == null)
            {
                entityInfo.SetValue(DateTime.Now);
            }
        }
        // 编辑/更新
        else if (entityInfo.OperationType == DataFilterType.UpdateByObject)
        {
            if (entityInfo.PropertyName == "UpdateTime")
                entityInfo.SetValue(DateTime.Now);
        }
    }

    public override void OnLogExecuting(string sql, SugarParameter[] pars)
    {
        base.OnLogExecuting(sql, pars);
    }
}

public class BasicAuthenticationMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _jwtKey = "YourSuperSecretKey1234567890123456"; // 请替换为您自己的密钥

    public BasicAuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Path == "/login")
        {
            await _next(context);
        }
        else if (context.Request.Path == "/")
        {
            if (!context.Request.Headers.ContainsKey("Authorization"))
            {
                // 检查 'Authorization' 头
                // 返回登录页面
                context.Response.ContentType = "text/html";

                await context.Response.WriteAsync(@"
<!DOCTYPE html>
<html lang=""zh-CN"">
<head>
    <meta charset=""UTF-8"">
    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
    <title>登录页面</title>
    <script src=""https://unpkg.com/axios/dist/axios.min.js""></script>
    <style>
        body {
            font-family: Avenir, Helvetica, Arial, sans-serif;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .login-form {
            width: 400px;
            padding: 20px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }
        .login-form h2 {
            text-align: center;
            margin-bottom: 20px;
        }
        .login-form label {
            display: block;
            margin-bottom: 8px;
        }
        .login-form input {
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .login-form button {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        .login-form button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class=""login-form"">
        <h2>用户登录</h2>
        <form id=""loginForm"" onsubmit=""handleLogin(event)"">
            <label for=""username"">用户名</label>
            <input type=""text"" id=""username"" placeholder=""请输入用户名"" required>
            <label for=""password"">密码</label>
            <input type=""password"" id=""password"" placeholder=""请输入密码"" required>
            <button type=""submit"">登录</button>
        </form>
    </div>

    <script>
        function handleLogin(event) {
            event.preventDefault(); // 阻止默认提交行为
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            const request = axios.create({
                            baseURL: 'http://localhost:5016'
            })

            // 设置请求拦截器，在发送请求时添加 Authorization 头
            request.interceptors.request.use((config) => {
                const token = localStorage.getItem('token'); // 从 localStorage 获取 token
                    if (token) {
                        config.headers.Authorization = `Bearer ${token}`; // 将 token 添加到 Authorization 头
                    }
                    return config;
                }, (error) => {
                    return Promise.reject(error);
                });

            request.get('/login?username='+username+'&password='+password)
                   .then((response)=>{
                                    const data = response.data;
                                    console.log('数据获取成功', response.data)
                                    localStorage.setItem('token', data.token);
                                    window.location.reload(); // 登录成功后刷新页面
                               })
                               .catch((error)=>{
                                    console.log(error);
                                    alert('登录失败，请检查用户名或密码。');
                               })


            
        }
    </script>
</body>
</html>

");




                return; // 终止处理
            }
        }


        // 如果 Authorization 头存在，继续处理请求
        await _next(context);
    }
}

public class CookieAuthenticationMiddleware
{
    private readonly RequestDelegate _next;

    public CookieAuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {

        if (context.Request.Cookies.TryGetValue("token", out var authCookie))
        {

        }
        else
        {

        }



        //// 尝试获取名为 "auth" 的Cookie
        //if (!context.Request.Cookies.TryGetValue("token", out var authCookie))
        //{
        //    // 如果 Cookie 不存在或不合法，返回登录页面
        //    context.Response.ContentType = "text/html";
        //    await context.Response.WriteAsync(GetLoginHtml());
        //    return; // 终止请求
        //}

        // 如果通过验证，继续处理请求
        await _next(context);
    }

    private bool ValidateToken(string token)
    {
        // 在这里实现你的JWT验证逻辑
        // 示例：解析和验证Token
        return token == "ExampleToken"; // 示例逻辑，请根据实际情况实现
    }


    private string GetLoginHtml()
    {
        return @"
                <!DOCTYPE html>
<html lang=""zh-CN"">
<head>
    <meta charset=""UTF-8"">
    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
    <title>登录页面</title>
    <script src=""https://unpkg.com/axios/dist/axios.min.js""></script>
    <style>
        body {
            font-family: Avenir, Helvetica, Arial, sans-serif;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .login-form {
            width: 400px;
            padding: 20px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }
        .login-form h2 {
            text-align: center;
            margin-bottom: 20px;
        }
        .login-form label {
            display: block;
            margin-bottom: 8px;
        }
        .login-form input {
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .login-form button {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        .login-form button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class=""login-form"">
        <h2>用户登录</h2>
        <form id=""loginForm"" onsubmit=""handleLogin(event)"">
            <label for=""username"">用户名</label>
            <input type=""text"" id=""username"" placeholder=""请输入用户名"" required>
            <label for=""password"">密码</label>
            <input type=""password"" id=""password"" placeholder=""请输入密码"" required>
            <button type=""submit"">登录</button>
        </form>
    </div>

    <script>
        function handleLogin(event) {
            event.preventDefault(); // 阻止默认提交行为
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            const request = axios.create({
                            baseURL: 'http://localhost:5016'
            })

            // 设置请求拦截器，在发送请求时添加 Authorization 头
            request.interceptors.request.use((config) => {
                const token = localStorage.getItem('token'); // 从 localStorage 获取 token
                    if (token) {
                        config.headers.Authorization = `Bearer ${token}`; // 将 token 添加到 Authorization 头
                    }
                    return config;
                }, (error) => {
                    return Promise.reject(error);
                });

            request.get('/login?username='+username+'&password='+password)
                   .then((response)=>{
                                    const data = response.data;
                                    console.log('数据获取成功', response.data)
                                    localStorage.setItem('token', data.token);
                                    window.location.reload(); // 登录成功后刷新页面
                               })
                               .catch((error)=>{
                                    console.log(error);
                                    alert('登录失败，请检查用户名或密码。');
                               })


            
        }
    </script>
</body>
</html>
            ";
    }
}